package com.faintlight.service.impl;

import com.faintlight.model.Sentence;
import com.faintlight.repository.SentenceRepository;
import com.faintlight.service.SentenceService;
import com.faintlight.exception.WarmException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SentenceServiceImpl implements SentenceService {

    private static final Logger logger = LoggerFactory.getLogger(SentenceServiceImpl.class);

    private final SentenceRepository sentenceRepository;

    @Override
    @Transactional
    public Sentence saveSentence(Sentence sentence) {
        logger.info("📌 保存句子: 内容长度={}", sentence.getContent().length());
        Sentence saved = sentenceRepository.save(sentence);
        logger.info("✅ 句子保存成功, ID={}", saved.getId());
        return saved;
    }


    @Override
    public List<Sentence> getUserSentences(Long userId) {
        return sentenceRepository.findByCollectedBy_IdOrderByCreatedAtDesc(userId);
    }
    @Override
    public List<Sentence> getSystemRecommendations() {
        logger.info("📖 获取系统推荐句子");
        List<Sentence> sentences = sentenceRepository.findBySystemRecommendedTrue();
        logger.info("✅ 获取成功, 共 {} 条推荐", sentences.size());
        return sentences;
    }

    @Override
    @Transactional
    public void deleteSentence(Long id, Long userId) {
        Sentence sentence = sentenceRepository.findById(id)
                .orElseThrow(() -> new WarmException("未找到句子"));
        if (sentence.getCollectedBy() != null && !sentence.getCollectedBy().getId().equals(userId)) {
            throw new WarmException("没有权限删除这条句子");
        }
        sentenceRepository.delete(sentence);
        logger.info("✅ 句子删除成功, ID={}", id);
    }
    @Override
    public Long getUserSentenceCount(Long userId) {
        return sentenceRepository.countByCollectedBy_Id(userId);
    }
}